package kassiopeia.agent.internal;

import java.util.Properties;
import kassiopeia.agent.AgentIDHolder;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.Ordered;
import org.springframework.core.io.ClassPathResource;

public class AgentIDPropertyConfigurer extends PropertyPlaceholderConfigurer {

    public static final String AGENT_ID_PROPERTY_KEY = "kassiopeia.agent.id";

    private String agentID;

    public AgentIDPropertyConfigurer() {
        setOrder(Ordered.HIGHEST_PRECEDENCE);
        setIgnoreUnresolvablePlaceholders(true);
        setIgnoreResourceNotFound(false);

        agentID = AgentIDHolder.getThisAgentId();
    }

    public AgentIDPropertyConfigurer(String location) {
        this();
        setLocation(new ClassPathResource(location));
    }

    @Override
    protected String resolvePlaceholder(String placeholder, Properties props) {
        if (placeholder.equals(AGENT_ID_PROPERTY_KEY)) {
            if (props.containsKey(AGENT_ID_PROPERTY_KEY)) {
                return props.getProperty(AGENT_ID_PROPERTY_KEY);
            }

            return agentID;
        }
        return null;
    }
}
